//
//  LFGlobalUserCountsViewModel.swift
//  SDAutoWeibo
//
//  Created by 刘健 on 16/3/23.
//  Copyright © 2016年 Clemmie. All rights reserved.
//

import UIKit

class LFGlobalUserAccountsViewModel: NSObject {
 
    //创建单例 全局来访问账号
    static let sharedUserAccounts = LFGlobalUserAccountsViewModel()
    
   private override init() {
        super.init()
        
        //从沙盒里加载账号
        userAccounts = unarchiverUserCounts()
 
    }
    
      //MARK: -- 属性
    //保存账号
    var userAccounts: LFUserAccounts?
    
    //用户是否登录
    var userLogin: Bool {
        get {
            if userAccounts != nil {
                
                return true
            }
            return false
        }
    }
   
    //沙盒的路径
    private let userAccountsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/userCounts.plist")
   
    
    //MARK : -- 网络请求获取access_token
    //闭包 completion: (erron:NSError?) ->()     记录保存成功，或失败
    func loadAccesstoken(code: String, completion: (error:NSError?) ->()) {
        
        //1.请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //2.请求参数
        let parameters = [
            "client_id" : LFClient_id,
            "client_secret" :LFClient_secret,
            "code" : code,
            "redirect_uri" : LFRedirect_uri
        ]
        
        //3.网络请求账号数据
        LFHTTPManager.sharedManager.POSTData(urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                completion(error: error)
                return
            }
            //字典转模型，并且赋值
          self.userAccounts = LFUserAccounts(dict: result!)
            //保存沙盒
            self.archiverUserCounts()
            completion(error: nil)
        }
    }
    
      //MARK: -- 请求用户信息
    func loadUserAccountsMessage(completion: (error:NSError?) ->()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = [
            "access_token" : userAccounts!.access_token!,
            "uid" : userAccounts!.uid!
        ]
        
        LFHTTPManager.sharedManager.GETData(urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                completion(error: error)
                print("\(error)")
                return
            }
            
            self.userAccounts?.screen_name = result!["screen_name"] as? String
            self.userAccounts?.avatar_large = result!["avatar_large"] as? String
            
            //保存沙盒
            self.archiverUserCounts()
            completion(error: nil)
        }
    }

      //MARK: -- 保存和读取
    //保存到沙盒
    private func archiverUserCounts() {
        
        if (userAccounts != nil) {
             NSKeyedArchiver.archiveRootObject(userAccounts!, toFile:userAccountsPath!)
        }
   
    }
    
    //解档数据
    private func unarchiverUserCounts() -> LFUserAccounts? {
        
        //1.拿出的账号
      let account =  NSKeyedUnarchiver .unarchiveObjectWithFile(userAccountsPath!) as? LFUserAccounts
        
        //2.判断是否过期
        if  (account != nil && account?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending) {
            
            return account!
        }
        return nil
    }
    
    
}
